package camuyen.ltwlibrary.controller;

import camuyen.ltwlibrary.dao.AuthorDao;
import camuyen.ltwlibrary.dao.BookDao;
import camuyen.ltwlibrary.dao.CategoryDao;
import camuyen.ltwlibrary.model.Author;
import camuyen.ltwlibrary.model.Book;
import camuyen.ltwlibrary.model.Category;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // book info
        String title = "";
        List<Long> categories = new ArrayList<Long>();
        List<Long> authors = new ArrayList<Long>();
        String publishedDate = "";
        String summary = "";
        String filePath = "";

        // upload path
        String uploadPath = request.getSession().getServletContext().getRealPath("/upload");
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(request);
            System.out.println("items.size(): " + items.size());
            for (FileItem item: items) {
                if (!item.isFormField()) {
                    filePath = uploadPath + File.separator + item.getName();
                    item.write(new File(filePath));
                } else {
                    System.out.println(item.getFieldName() + ":" + item.getString());
                    if (item.getFieldName() != null && item.getFieldName().equalsIgnoreCase("title"))
                        title = item.getString();

                    if (item.getFieldName() != null && item.getFieldName().equalsIgnoreCase("author"))
                        authors.add(Long.valueOf(item.getString()));

                    if (item.getFieldName() != null && item.getFieldName().equalsIgnoreCase("category"))
                        categories.add(Long.valueOf(item.getString()));

                    if (item.getFieldName() != null && item.getFieldName().equalsIgnoreCase("publishedDate"))
                        publishedDate = item.getString();

                    if (item.getFieldName() != null && item.getFieldName().equalsIgnoreCase("summary"))
                        summary = item.getString();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Book newBook = new Book();
        newBook.setTitle(title);
        newBook.setCategories(CategoryDao.getCategoriesByListId(categories));
        newBook.setAuthors(AuthorDao.getAuthorsByListId(authors));
        newBook.setPublishedDate(publishedDate);
        newBook.setSummary(summary);
        BookDao.saveBook(newBook);

        response.sendRedirect("upload.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

//    private String getUploadPath(HttpSession session) {
//        return session.getServletContext().getRealPath(UPLOAD_DIRECTORY);
//    }
}
